package cn.uce.cc.rest.control;

import cn.uce.cc.entity.CcAgent;
import cn.uce.cc.srv.biz.impl.CcAgentBiz;
import cn.uce.cc.srv.utils.CallCenterApiUtil;
import cn.uce.core.cache.CacheManager;
import cn.uce.core.cache.base.ICache;
import cn.uce.utils.StringUtil;
import cn.uce.web.authorg.vo.DictDataVo;
import cn.uce.web.common.base.BaseController;
import cn.uce.web.common.base.CurrentUser;
import cn.uce.web.common.util.WebUtil;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Iterator;
import java.util.List;

/**
 * Created by zhaocan on 2018/4/25.
 * 集成呼叫中心话务条
 */
@Controller
@RequestMapping("/callCenter/phone")
public class CallCenterBarController{
    private static final long serialVersionUID = -4911054117941551962L;
    
    private static final String ERROR_CODE = "errcode";
    
    private Logger log = LoggerFactory.getLogger(getClass());

    @Resource
    private CcAgentBiz ccAgentBiz;
    @Autowired
    private CallCenterClient callCenterClient;
    /**
     * 呼叫中心话务条页面
     */
    @RequestMapping(value = "/phonebarIndex")
    public String phonebarIndex(Model model,final HttpServletRequest request){
        String webUrl = "";
        String protocol = "http";
        //默认专线
        webUrl = callCenterClient.getWebUrl();
        String yunHuIp = protocol+"://"+callCenterClient.getYunHuIp();
        //获取当前登陆人
        String userCode = null;
        String agentId =null;
        String agentName=null;
        //sandi默认写死
        String agtPwd = "123456";
        String domain = callCenterClient.getDomain();
        String logOutOff = "0";
        String readyOff = "0";
        Integer readyDelay = 0;
        try {
            ICache<String, List<DictDataVo>> fspDictDateCache = CacheManager.getInstance().getCache("DictDataCache");
            List<DictDataVo> cclist = fspDictDateCache.get("CC_MAIN_LOG_OUT");
            List<DictDataVo> ccReadylist = fspDictDateCache.get("CC_CALL_READY");
            List<DictDataVo> ccRreadyDelaylist = fspDictDateCache.get("CC_CALL_READY_DELAY");
            if(!cclist.isEmpty()){
                logOutOff = ObjectUtils.isEmpty(cclist.get(0).getTypeCode())?"0":cclist.get(0).getTypeCode();
            }
            if(!ccReadylist.isEmpty()){
                readyOff = ObjectUtils.isEmpty(ccReadylist.get(0).getTypeCode())?"0":ccReadylist.get(0).getTypeCode();
            }
            if(!ccRreadyDelaylist.isEmpty()){
                readyDelay = ObjectUtils.isEmpty(ccRreadyDelaylist.get(0).getTypeCode())?0:Integer.parseInt(ccRreadyDelaylist.get(0).getTypeCode());
            }
            //根据当前登录人员工编码获取openId
            CurrentUser currentUser = WebUtil.getCurrentUser();
            if(currentUser != null && StringUtil.isNotEmpty(currentUser.getEmpCode())){
                userCode = currentUser.getEmpCode();
                agentName = currentUser.getEmpName();
                CcAgent ccAgent = ccAgentBiz.getCcAgentByUserId(currentUser.getEmpCode());
                if(ccAgent != null && StringUtil.isNotEmpty(ccAgent.getCtiOpenid())){
                    agentId = ccAgent.getCtiOpenid();
                    if(StringUtils.isNotEmpty(ccAgent.getCtiPwd())){
                        agtPwd = ccAgent.getCtiPwd();
                    }
                }else{
                    throw new Exception("用户未配置ctiOpenId或cti密码");
                }
            }
        }catch (Exception e){
            //呼叫中心初始化异常太多暂时注释
            log.debug("呼叫中心话务条初始化信息查询接口异常",e);
        }
        //用户id
        model.addAttribute("agentId",agentId);
        //用户账号
        model.addAttribute("agentName",agentName);
        //用户账号
        model.addAttribute("userCode",userCode);
        //呼叫中心用户密码
        model.addAttribute("agtPwd",agtPwd);
        model.addAttribute("webUrl",webUrl);
        model.addAttribute("domain",domain);
        model.addAttribute("satisfactionDeviceId",callCenterClient.getSatisfactionDeviceId());
        model.addAttribute("yunHuIp",yunHuIp);
        model.addAttribute("yunHuIpListen",callCenterClient.getYunHuIpListen());
        model.addAttribute("logOutOFF",logOutOff);
        model.addAttribute("readyOFF",readyOff);
        model.addAttribute("readyDelay",readyDelay);
        return "callcenter/phonebar_index";
    }

    /**
     * 呼叫中心话务条页面 老呼叫方式
     */
    @RequestMapping(value = "/phonebarIndexBak")
    public String phonebarIndexBak(Model model,final HttpServletRequest request) {
        String webUrl = "";
        String hostUrl = "";
        String protocol = "http";
        //1121 修改西安话务中心逻辑 Start
        //获取当前登陆人
        String empCode = WebUtil.getCurrentUser().getEmpCode();
        ICache<String, List<DictDataVo>> fspDictDateCache = CacheManager.getInstance().getCache("DictDataCache");
        List<DictDataVo> list = fspDictDateCache.get("CALL_CS_LIST_XIAN");
        List<DictDataVo> cclist = fspDictDateCache.get("CC_PROTOCOL");
        if(!cclist.isEmpty()){
            protocol = cclist.get(0).getTypeCode();
        }
        //默认专线
        webUrl = protocol+"://"+callCenterClient.webUrl;
        hostUrl = protocol+"://"+callCenterClient.hostUrl;
        if (null != list && list.size() > 0 ){
            Iterator<DictDataVo> iterator = list.iterator();
            while(iterator.hasNext()) {
                DictDataVo ddv = iterator.next();
                if(empCode.equals(ddv.getTypeCode())){
                    webUrl = protocol+"://"+callCenterClient.pubWebUrl;
                    hostUrl = protocol+"://"+callCenterClient.pubHostUrl;
                    break;
                }
            }
        }
        //1121 修改西安话务中心逻辑 End
        //接口地址
        model.addAttribute("hostUrl", hostUrl);
        String userPwd = null;
        String userCode = null;
        String agentId =null;
        String groups =null;
        String agentName=null;
        //sandi默认写死
        String agtPwd = "123456";
        String cloudUrl = callCenterClient.cloudUrl;
        try {
            //获取accessToken
            String accessTokenStr = CallCenterApiUtil.getAccessToken(hostUrl,callCenterClient.clientId, callCenterClient.clientSecret);
            JSONObject jsonAccessToken = JSONObject.parseObject(accessTokenStr);
            String errcode = (String) jsonAccessToken.get(ERROR_CODE);
            if ("0".equals(errcode)) {
                String accessToken = (String) jsonAccessToken.get("accessToken");
                //获取userId/userCode//此处需改为动态获取，根据登陆用户。
                String openId = callCenterClient.openId;
                //根据当前登录人员工编码获取openId
                CurrentUser currentUser = WebUtil.getCurrentUser();
                if(currentUser != null && StringUtil.isNotEmpty(currentUser.getEmpCode())){
                    CcAgent ccAgent = ccAgentBiz.getCcAgentByUserId(currentUser.getEmpCode());
                    if(ccAgent != null && StringUtil.isNotEmpty(ccAgent.getCtiOpenid())){
                        openId = ccAgent.getCtiOpenid();
                    }
                }

                String userInfoStr = CallCenterApiUtil.getuserinfo(hostUrl,accessToken, callCenterClient.clientId, openId);
                JSONObject jsonUserInfo = JSONObject.parseObject(userInfoStr);
                errcode = (String) jsonUserInfo.get(ERROR_CODE);
                if ("0".equals(errcode)) {
                    JSONObject userInfo = JSONObject.parseObject(jsonUserInfo.getString("value"));
                    userCode = userInfo.getString("userCode");
                    String userId =userInfo.getString("userId");
                    //获取坐席
                    String agentStr = CallCenterApiUtil.getAgentByUserId(hostUrl,accessToken, callCenterClient.clientId, openId, userId);
                    JSONObject jsonAgent = JSONObject.parseObject(agentStr);
                    errcode = (String) jsonAgent.get(ERROR_CODE);
                    if ("0".equals(errcode)) {
                        JSONObject agent = JSONObject.parseObject(jsonAgent.getString("value"));
                        userPwd = agent.getString("password");
                        groups = agent.getString("groups");
                        agentId = agent.getString("agentid");
                        agentName = agent.getString("name");
                    }
                }
                if(currentUser != null && StringUtil.isNotEmpty(currentUser.getEmpName())){
                    agentName = currentUser.getEmpName();
                }
            }
        }catch (Exception e){
            //呼叫中心初始化异常太多暂时注释
            log.debug("呼叫中心话务条初始化信息查询接口异常",e);
        }
        //用户id
        model.addAttribute("agentId",agentId);
        //用户账号
        model.addAttribute("agentName",agentName);
        //用户密码
        model.addAttribute("userPwd",userPwd);
        //用户账号
        model.addAttribute("userCode",userCode);
        //用户账号
        model.addAttribute("groups",groups);
        //呼叫中心用户密码
        model.addAttribute("agtPwd",agtPwd);
        model.addAttribute("webUrl",webUrl);
        model.addAttribute("cloudUrl",cloudUrl);
        return "callcenter/phonebar_index";
    }

    /**
     * 呼叫中心话务条相关页面
     */
    @RequestMapping(value = "/frmAgtMonitor")
    public String frmAgtMonitor() {
        return "callcenter/AgtMonitor";
    }

    /**
     * 呼叫中心话务条相关页面
     */
    @RequestMapping(value = "/frmRemoteCTI")
    public String frmRemoteCTI(Model model) {
        return "callcenter/RemoteCTI";
    }
    /**
     * 呼叫中心下载录音功能
     */
    @RequestMapping(value = "/downloadRecord")
    public void downloadRecord(final HttpServletRequest request,
                               final HttpServletResponse response) {
        String webUrl = "";
        String hostUrl = "";
        String protocol = "http";
        //1121 修改西安话务中心逻辑 Start
        //获取当前登陆人
        String empCode = WebUtil.getCurrentUser().getEmpCode();
        ICache<String, List<DictDataVo>> fspDictDateCache = CacheManager.getInstance().getCache("DictDataCache");
        List<DictDataVo> list = fspDictDateCache.get("CALL_CS_LIST_XIAN");
        List<DictDataVo> cclist = fspDictDateCache.get("CC_PROTOCOL");
        if(!cclist.isEmpty()){
            protocol = cclist.get(0).getTypeCode();
        }
        //hostUrlReg = protocol+"://10.3.3.151:9802";
        //hostUrl = protocol+"://116.228.114.190:9801/VenusRest";
        webUrl = protocol+"://"+callCenterClient.webUrl;
        hostUrl = protocol+"://"+callCenterClient.hostUrl;
        if (null != list && list.size() > 0 ){
            Iterator<DictDataVo> iterator = list.iterator();
            while(iterator.hasNext()) {
                DictDataVo ddv = iterator.next();
                if(empCode.equals(ddv.getTypeCode())){
                    //hostUrlReg = protocol+"://116.228.114.190:9802";
                    //hostUrl = protocol+"://116.228.114.190:9801/VenusRest";
                    webUrl = protocol+"://"+callCenterClient.pubWebUrl;
                    hostUrl = protocol+"://"+callCenterClient.pubHostUrl;
                    break;
                }
            }
        }
        //呼叫ID
        String callId =request.getParameter("callId");
        //呼叫子ID
        String subId =request.getParameter("subId");
        //录音所属组织ID
        String organizerId =request.getParameter("organizerId");
       /* callId="1527359289";
        subId="1";
        organizerId="1";*/
        response.reset();
        OutputStream out = null;
        try {
            //获取accessToken
            String accessTokenStr = CallCenterApiUtil.getAccessToken(hostUrl,callCenterClient.clientId, callCenterClient.clientSecret);
            JSONObject jsonAccessToken = JSONObject.parseObject(accessTokenStr);
            String errcode = (String) jsonAccessToken.get(ERROR_CODE);
            if ("0".equals(errcode)) {
                String accessToken = (String) jsonAccessToken.get("accessToken");
                //获取userId/userCode
                //此处需改为动态获取，根据登陆用户。
                String openId = callCenterClient.openId;
                //根据当前登录人员工编码获取openId
                CurrentUser currentUser = WebUtil.getCurrentUser();
                if(currentUser != null && StringUtil.isNotEmpty(currentUser.getEmpCode())){
                    CcAgent ccAgent = ccAgentBiz.getCcAgentByUserId(currentUser.getEmpCode());
                    if(ccAgent != null && StringUtil.isNotEmpty(ccAgent.getCtiOpenid())){
                        openId = ccAgent.getCtiOpenid();
                    }
                }

                if (callId == null || callId.trim().length() == 0
                        || subId == null || subId.trim().length() == 0
                        || organizerId == null || organizerId.trim().length() == 0) {
                    log.error("呼叫中心录音下载参数不完整");
                }else{
                    byte[] bytes = CallCenterApiUtil.downloadRecord(hostUrl,accessToken, callCenterClient.clientId, openId, callId, subId, organizerId);
                    try(
                        InputStream inputStream = new ByteArrayInputStream(bytes);
                    ){
                        response.setContentType("application/x-msdownload");
                        response.setHeader("Content-Disposition", "attachment; filename=" + callId + ".wav");

                        byte[] buf = new byte[1024];
                        int len = 0;

                        out = response.getOutputStream();
                        while ((len = inputStream.read(buf)) > 0){
                            out.write(buf, 0, len);
                        }
                    }catch(IOException io){
                        log.error("IO异常",io);
                    }

                }

            }
        } catch (Exception e) {
            log.error("未知异常:", e);
        }
    }
}
